<template>
  <div>
    <MyComponent>
      <template #content>
        <el-container>
          <el-header style="display: flex;justify-content: space-between;align-items: center">
            <h2>图书信息</h2>
            <el-button style="width: 100px;height: 45px" type="primary" @click="showDialog('add')">添加图书</el-button>
          </el-header>
          <el-main>
            <div class="search" style="display: flex;flex-direction: row;padding-bottom: 5px">
              <el-input style="margin-right: 10px" type="text" v-model="searchParams.name" placeholder="请输入书名"></el-input>
              <el-input style="margin-right: 10px"  type="text" v-model="searchParams.author" placeholder="请输入作者"></el-input>
              <el-input style="margin-right: 10px"  type="text" v-model="searchParams.publisher" placeholder="请输入出版社"></el-input>
              <el-button type="primary" @click="searchBooks">搜索</el-button>
              <el-button type="danger" @click="reset">重置</el-button>
            </div>
            <el-table :data="books" style="width: 100%;height:450px;overflow-y: scroll">
              <el-table-column prop="name" label="书名"></el-table-column>
              <el-table-column prop="author" label="作者"></el-table-column>
              <el-table-column prop="publisher" label="出版社"></el-table-column>
              <el-table-column prop="price" label="价格"></el-table-column>
              <el-table-column prop="category.name" label="分类"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="text" @click="editBook(scope.row)">编辑</el-button>
                  <el-button type="text" @click="deleteBook(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-main>

        </el-container>

        <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" width="30%">
          <el-form :model="bookForm" ref="bookForm" :rules="rules" label-width="80px">
            <el-form-item label="书名" prop="name">
              <el-input v-model="bookForm.name"></el-input>
            </el-form-item>
            <el-form-item label="作者" prop="author">
              <el-input v-model="bookForm.author"></el-input>
            </el-form-item>
            <el-form-item label="出版社" prop="publisher">
              <el-input v-model="bookForm.publisher"></el-input>
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input v-model="bookForm.price"></el-input>
            </el-form-item>
            <el-form-item label="分类" prop="category">
            <el-select v-model="bookForm.category" placeholder="请选择分类">
              <!-- 循环遍历分类列表，生成选项 -->
              <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id">
              </el-option>
            </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="handleCloseDialog">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </div>
        </el-dialog>
      </template>
    </MyComponent>
  </div>
</template>

<script>
import MyComponent from '@/components/backend.vue';
import axios from '@/request/request';


export default {
  components: {
    MyComponent,
  },
  data() {
    return{
      searchParams: {
        name: '',
        author: '',
        publisher: ''
      },
      selectedCategory: '',
      categories: [],
      books: [], // 存放图书列表
      dialogVisible: false, // 控制对话框显示隐藏
      dialogTitle: '', // 对话框标题
      bookForm: { // 表单数据
        name: '',
        author: '',
        publisher:'',
        price: null,
        category :null


      },
      rules: { // 表单校验规则
        name: [
          { required: true, message: '请输入书名', trigger: 'submit' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'submit' }
        ],
        publisher: [
          { required: true, message: '请输入出版社', trigger: 'submit' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'submit' }
        ],

      }
    }
  },
  mounted() {
    this.fetchCategories();
    // 在组件挂载完成后获取图书列表
    this.getBooks();
  },
  methods: {
    reset(){
      this.searchParams={}
      this.getBooks()
    },
    handleCloseDialog() {
      this.dialogVisible = false;
    },
    fetchCategories() {
      axios.get('http://localhost:8080/api/categories')
          .then(response => {
            this.categories = response.data; // 将获取的分类数据保存到组件中
          })
          .catch(error => {
            console.error('Failed to fetch categories: ' + error);
          });
    },
    getBooks() {
      axios.get('/api/books/search')
          .then(response => {
            this.books = response.data;
          })
          .catch(error => {
            console.error('获取图书列表失败：', error);
          });
    },
    searchBooks() {
      axios.get('/api/books/search', {
        params: this.searchParams
      })
          .then(response => {
            // 处理搜索结果
            this.books = response.data;
          })
          .catch(error => {
            console.error('搜索失败:', error);
          });
    },


    showDialog(type, bookData = {}) {
      // 根据不同的操作类型设置对话框标题和表单数据
      if (type === 'add') {
        this.dialogTitle = '添加图书';
        this.bookForm = {
          name: '',
          author: '',
          publisher:'',
          price: null,
          category: null
        };
      } else if (type === 'edit') {
        this.dialogTitle = '编辑图书';
        this.bookForm = {
          id: bookData.id|| '',
          name: bookData.name || '',
          author: bookData.author || '',
          publisher: bookData.publisher || '',
          price: bookData.price || null,
          category: bookData.category.id || null
        };
      }
      this.dialogVisible = true;
    },
    submitForm() {
      this.bookForm.category = { "id": this.bookForm.category };
      this.$refs.bookForm.validate(valid => {
        if (valid) {
          // 表单校验通过，根据表单数据进行新增或编辑操作
          if (this.bookForm.id) {
            // 编辑操作
            axios.put(`/api/books/${this.bookForm.id}`, this.bookForm)
                .then(response => {
                  this.dialogVisible = false;
                  this.getBooks();
                })
                .catch(error => {
                  console.error('编辑图书失败：', error);
                });
          } else {
            console.log(this.bookForm)
            // 新增操作
            axios.post('/api/books', this.bookForm)
                .then(response => {
                  this.getBooks();
                  this.dialogVisible = false;
                })
                .catch(error => {
                  console.error('添加图书失败：', error);
                });
          }
        }
      });
      this.bookForm.category = null;
    },
    editBook(book) {
      // 编辑图书，打开对话框并传入图书数据
      this.showDialog('edit', book);
    },
    deleteBook(book) {
      // 删除图书
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`/api/books/${book.id}`)
            .then(response => {
              this.getBooks();
            })
            .catch(error => {
              console.error('删除图书失败：', error);
            });
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
    }
};
</script>
